package br.com.simora.login;

import java.util.Date;
import java.util.ResourceBundle;

import javax.inject.Inject;

import org.apache.commons.codec.binary.Base64;

import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Result;
import br.com.simora.component.AcessSession;
import br.com.simora.component.PasswordEncryptionService;
import br.com.simora.component.StringUteis;
import br.com.simora.controller.BasicController;
import br.com.simora.controller.HomeController;
import br.com.simora.usuario.Usuario;
import br.com.simora.usuario.UsuarioDAO;

@Controller
public class LoginController extends BasicController {
	@Inject private UsuarioDAO usuarioDAO;
	@Inject private AcessSession session;

	public LoginController(Result result, ResourceBundle bundle,
			UsuarioDAO usuarioDAO, AcessSession session) {
		this.result = result;
		this.bundle = bundle;
		this.usuarioDAO = usuarioDAO;
		this.session = session;
	}
	
	public LoginController(){}

	@Path(value = "/login/entrar")
	@Post
	public void entrar(Usuario usuario) {
		if(usuario != null){
			if(StringUteis.isEmpty(usuario.getEmail())){
    			mensagemErro("erro.email.usuario.obrigatorio");
    		}
    		if(StringUteis.isEmpty(usuario.getSenha())){
    			mensagemErro("erro.senha.usuario.obrigatorio");
    		}
    		if(resultPossui(ERROR) && resultPossuiConteudo(ERROR)){ redirect(); return;}
			Usuario temp = usuarioDAO.recuperaUsuariosPorEmail(usuario.getEmail());
			if(temp != null){
				boolean failExp=false;
				
				if(temp.getDataExpiracao()!=null){
					if(temp.getDataExpiracao().compareTo(new Date())<0){
						mensagemErro("erro.usuario.conta.expirada");
						failExp=true;
						result.redirectTo(HomeController.class).index();
					}
						
				}
				if(!failExp){
					PasswordEncryptionService pas = new PasswordEncryptionService();
					try {
						Boolean retorno = pas.authenticate(usuario.getSenha(), Base64.decodeBase64(temp.getSenha()), Base64.decodeBase64(temp.getChave()));
						if(retorno){
							session.setNome(temp.getNome());
							session.setUsuario(temp);
							if("A".equals(temp.getTipo())){
								result.redirectTo(HomeController.class).indexAdmin();
							}
							if("U".equals(temp.getTipo())){
								result.redirectTo(HomeController.class).indexUsuario();
							}
						} else {
							mensagemErro("erro.usuario.nao.encontrado");
							result.redirectTo(HomeController.class).index();
						}
					} catch (Exception e) {
						mensagemErro("erro.usuario.nao.encontrado");
						result.redirectTo(HomeController.class).index();
					}
				}
				
			} else {
				mensagemErro("erro.usuario.nao.encontrado");
				result.redirectTo(HomeController.class).index();
			}
		} else {
			mensagemErro("erro.ao.recuperar");
			result.redirectTo(HomeController.class).index();
		}
    }

	@Override
	protected void redirect() {}
	
}